package com.heima.user.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import com.heima.utils.common.IdCardUtils;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
//@Transactional
@Slf4j
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {

    /**
     * 查询列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadListByStatus(AuthDto dto) {
        // 1 参数检查(1.检查从前端传过来的dto是否为空2.检查分页)
        if (dto==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();//检查分页
        //2.1检查完参数之后要把查询页面的那个框创建好（不带记录数据的那种）
        IPage<ApUserRealname> page = new Page(dto.getPage(), dto.getSize());
        //2.2状态条件
        LambdaQueryWrapper<ApUserRealname> lambdaQuery = Wrappers.<ApUserRealname>lambdaQuery();
        lambdaQuery.eq(dto.getStatus()!=null,ApUserRealname::getStatus,dto.getStatus());
        //3.按照创建时间进行降序排序
        lambdaQuery.orderByDesc(ApUserRealname::getCreatedTime);
        //4.执行查询
        IPage<ApUserRealname> page1 = this.page(page, lambdaQuery);
        //5.封装分页并返回结果
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), page1.getTotal());
        pageResponseResult.setData(page1.getRecords());
        return pageResponseResult;

    }

    @Autowired
    ApUserMapper apUserMapper;

    /**
     *
     * @param dto
     * @param status 2代表审核失败  9代表审核通过
     * @return
     */
    @GlobalTransactional(timeoutMills = 60000,rollbackFor = Exception.class)
    @Override
    public ResponseResult updateStatusById(AuthDto dto, Short status) {
        //1.检查参数 id(认证信息)
        if(dto==null || dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"实名认证信息id参数错误！");
        }
       //2.查询实名认证信息
        ApUserRealname userRealname = getById(dto.getId());
        if (userRealname==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"实名认证信息不存在！");
        }
       //3.判断当前实名认证的状态(我们需要操作的是其状态为1的情况即待审核状态)
       if( userRealname.getStatus().intValue() !=1){
           return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_ALLOW,"审核的状态错误！");
       }
       //4.查询相关联的ap_user
        ApUser apUser = apUserMapper.selectById(userRealname.getUserId());
        if (apUser==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_ALLOW,"审核的状态错误！");
        }
       //5.修改实名认证的状态
       userRealname.setUpdatedTime(new Date());
        userRealname.setStatus(status);
        if (StringUtils.isNotBlank(dto.getMsg())) {
            userRealname.setReason(dto.getMsg());
        }
        updateById(userRealname); //修改实名认证状态
       //6.如果状态为9（表示审核通过，就需要在自媒体的表中添加一条记录）
        if(status.intValue()==2){
            return ResponseResult.okResult();
        }
        boolean b = IdCardUtils.checkIdCardInfo(userRealname.getIdno(), userRealname.getName());
        if (b==false){//表示校验的值为false
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"身份证校验不通过！");
        }
        WmUser wmUser = createWmUser(apUser);
        createAuthor(apUser,wmUser);
        return ResponseResult.okResult();
    }
    @Autowired
    ArticleFeign articleFeign;

    private void createAuthor(ApUser apUser, WmUser wmUser) {
        ResponseResult<ApAuthor> findResult = articleFeign.findByUserId(apUser.getId());
        if(findResult.getCode().intValue()!=0){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,findResult.getErrorMessage());
        }
        ApAuthor apAuthor = findResult.getData();
        if (apAuthor!=null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"对应的作者已存在！");
        }
        apAuthor = new ApAuthor();
        apAuthor.setCreatedTime(new Date());
        apAuthor.setName(wmUser.getName());
        apAuthor.setType(2); // 自媒体人类型
        apAuthor.setUserId(wmUser.getApUserId()); // APP 用户ID
        apAuthor.setWmUserId(wmUser.getId()); // 自媒体用户ID
        ResponseResult result = articleFeign.save(apAuthor);
        if(result.getCode().intValue()!=0){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,findResult.getErrorMessage());
        }

    }

    @Autowired
    WemediaFeign wemediaFeign;
    /**
     * 创建自媒体账户（此处就会涉及带远程调用即使用feign进行微服务之间的调用）
     * @param apUser
     * @return
     */

    private WmUser createWmUser(ApUser apUser) {
    //1.使用feign根据用户名称查询自媒体账户是否存在
        ResponseResult<WmUser> findResult = wemediaFeign.findByName(apUser.getName());
        if(findResult.getCode().intValue()!=0){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,findResult.getErrorMessage());
        }
        WmUser wmUser = findResult.getData();
        if (wmUser!=null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"对应的自媒体账户已存在！");
        }
        //2.如果不存在则创建自媒体账户
        wmUser = new WmUser();
        wmUser.setName(apUser.getName());
        wmUser.setSalt(apUser.getSalt());  // 盐
        wmUser.setPassword(apUser.getPassword()); // 密码
        wmUser.setPhone(apUser.getPhone());
        wmUser.setCreatedTime(new Date());
        wmUser.setType(0); // 个人
        wmUser.setApUserId(apUser.getId());  // app端用户id
        wmUser.setStatus(AdminConstants.PASS_AUTH.intValue());
        ResponseResult<WmUser> saveResult = wemediaFeign.save(wmUser);
        if(saveResult.getCode().intValue()!=0){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,findResult.getErrorMessage());
        }
        return saveResult.getData();
    }
}
